package com.sxjh.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sxjh.entity.Task;
import com.sxjh.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 定时删除过期未使用的派车单
 */
@Slf4j
@Component
public class ClearExpireTask {

    @Autowired
    private TaskService taskService;

    /**
     * 定时删除过期未使用的派车单
     */
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void clear() {
        //滞后10分钟删除
        LocalDateTime now = LocalDateTimeUtil.offset(LocalDateTimeUtil.now(), -10, ChronoUnit.MINUTES);
        log.info("==========查询过期未使用的派车单:{}", now);
        LambdaQueryWrapper<Task> query = new LambdaQueryWrapper<>();
        query.eq(Task::getStatus, 1);
        query.le(Task::getEndDate, now);
        query.isNull(Task::getTareAt);
        query.isNull(Task::getGrossAt);
        query.isNull(Task::getTareImg);
        query.isNull(Task::getGrossImg);
        query.eq(Task::getCurrNode, 0);
        query.orderByAsc(Task::getId);
        List<Task> list = taskService.list(query);
        if (CollUtil.isNotEmpty(list)) {
            //存在定时删除过期未使用的派车单
            log.info("==========过期未使用的派车单:{}", JSONUtil.toJsonStr(list));
            taskService.removeByIds(list.stream().map(Task::getId).collect(Collectors.toList()));
        }

    }


}